package com.weimei.conversionTreasure.viewModel;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import com.weimei.conversionTreasure.http.Repository;
import com.weimei.conversionTreasure.http.entity.BaseResult;
import com.weimei.conversionTreasure.utils.UserUtils;
import com.weimei.conversionTreasure.utils.ValidateUtils;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.observers.DisposableObserver;
import me.goldze.mvvmhabit.base.BaseModel;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

public class AddKhVM extends BaseViewModel<Repository> {
    public AddKhVM(@NonNull Application application, Repository model) {
        super(application, model);
    }

    public ObservableField<String> name = new ObservableField<>("");
    public ObservableField<String> phone = new ObservableField<>("");
    public ObservableField<String> wechat = new ObservableField<>("");
    public ObservableField<String> nots = new ObservableField<>("");
    public ObservableField<String> sid = new ObservableField<>("");

    public ObservableField<String> title = new ObservableField<>("添加客户");

    public BindingCommand saveClick = new BindingCommand(() -> save());
    public BindingCommand back = new BindingCommand(() -> finish());


    private void save() {
        if (ValidateUtils.isEmptyString(name.get())){
            ToastUtils.showShort("请输入姓名");
            return;
        }
        if (ValidateUtils.isEmptyString(phone.get())){
            ToastUtils.showShort("请输入联系方式");
            return;
        }

        Map<String,String> map = new HashMap<>();
         map.put("user_id", UserUtils.getUserAccount());
        map.put("name",name.get());
        map.put("phone",phone.get());
        map.put("wechat",wechat.get());
        map.put("nots",nots.get());

        map.put("sid",sid.get());
        map.put("types","客户");

        model.adddealer(map)
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(this)
                .doOnSubscribe(disposable -> {})
                .subscribe(new DisposableObserver<BaseResult>() {
                    @Override
                    public void onNext(BaseResult baseResult) {
                        if (baseResult.issucc){
                            ToastUtils.showShort(baseResult.msg);
                            finish();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
